package com.leetcode.题库;

/**
 * @author 覃国强
 * @date 2022-02-24 18:14
 */
public class 题库_0005_最长回文子串 {

  public static void main(String[] args) {
    Solution solution = new Solution();
    String s = "cbbd";
    System.out.println(solution.longestPalindrome(s));
  }

  static
  class Solution {
    public String longestPalindrome(String s) {
      if (s == null || s.length() < 1) {
        return s;
      }

      int maxLength = 1;
      int start = 0;

      char[] chars = s.toCharArray();
      for (int i = 0; i < chars.length - 1; ++i) {

        int len1 = palindromeLength(chars, i, i);
        int len2 = palindromeLength(chars, i, i + 1);
        int curMaxLength = Math.max(len1, len2);
        if (curMaxLength > maxLength) {
          maxLength = curMaxLength;
          start = i - (curMaxLength - 1) / 2;
        }
      }

      return new String(chars, start, maxLength);
    }

    private int palindromeLength(char[] chars, int left, int right) {
      while (left >= 0 && right < chars.length && chars[left] == chars[right]) {
        --left;
        ++right;
      }
      return right - left - 1;
    }

  }

}
